#import "UserManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"

@implementation UserManager
SYNTHESIZE_SINGLETON_FOR_CLASS(UserManager);

@synthesize isLogin,registerErrInfo,email,password,sessionId,userName,userId;

-(id)init{    
    self = [super init];
    isLogin = NO;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    email = [defaults stringForKey:@"email"];
    password = [defaults stringForKey:@"password"];
    if([email isEqualToString:@"null"]||[password isEqualToString:@"null"]){
        email = nil;
        password = nil;
    }
    registerErrInfo = @"";
    sessionId = nil;
    userName = nil;
    userId = nil;
    return self;
}

-(void) dealloc {
    PP_RELEASE(registerErrInfo);
    PP_RELEASE(email);
    PP_RELEASE(password);
    PP_RELEASE(sessionId);
    PP_RELEASE(userName);
    PP_RELEASE(userId);
    PP_RELEASE(home);
    PP_RELEASE(registerErrInfo);
    [super dealloc];
}

-(NSString *)loginWithRecord:(JokeViewController *)phome;
{
    home = phome;
    if(email == nil|| password == nil){
        Log(@"no record");
        return @"请重新登录";
    }
    
    NSString *url = LOGIN_URL(email, password, @"on");
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setUseCookiePersistence:YES];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *error = [request error];
    NSString *res;
    if(!error){
        res = [self requestLoginDone:request];
    }else{
        [self requestLoginWentWrong:request];
        res = @"网络异常,请重新登录";
    }
    return res;
}


#pragma ----------登录方法----------
-(NSString *)loginWithEmail:(NSString *)pEmail password:(NSString *)pPassword remember:(NSString *)pRemember
{
    NSString *url = LOGIN_URL(pEmail, pPassword, pRemember);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setUseCookiePersistence:YES];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *error = [request error];
    NSString *res;
    if(!error){
        self.email = pEmail;
        self.password = pPassword;
        //写入userDefault
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        [defaults setObject:email forKey:@"email"];
        [defaults setObject:password forKey:@"password"];
        
        res = [self requestLoginDone:request];
    }else{
        self.email = nil;
        self.password = nil;
        [self requestLoginWentWrong:request];
        res = @"网络异常,请稍后再试";
    }
    return res;
}


- (NSString *)requestLoginDone:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    NSString *res = @"";

    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr]; 
    [tJsonParser release], tJsonParser = nil;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        BOOL tIsLogin = [[(NSDictionary *)tJsonObjects objectForKey:@"is_login"] boolValue];
        if (tIsLogin) {
            NSString *tUserName = [(NSDictionary *)tJsonObjects objectForKey:@"user_name"];
            NSString *tUserId = [[(NSDictionary *)tJsonObjects objectForKey:@"user_id"] stringValue];
            NSArray *cookies = [ request responseCookies ];
//            Log(@"%@",cookies);
            for (NSHTTPCookie *cookie in cookies) {
                if ([[cookie name ] isEqualToString : @"webpy_session_id"]) {
                    self.isLogin = YES;
                    self.sessionId = [cookie value];
                    self.userName = tUserName;
                    self.userId = tUserId;
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:self];
                    break;
                }
            }
            Log ( @"userName=%@,userId=%@,sessionId=%@" ,self.userName,self.userId,self.sessionId);
        } else {
            res = [(NSDictionary *)tJsonObjects objectForKey:@"msg"];
            Log ( @"is_login : false");
            self.sessionId = nil;
            self.isLogin = NO;
        }
    }else{
        res = [(NSDictionary *)tJsonObjects objectForKey:@"msg"];
        Log ( @"failed : response parse failed");
        self.sessionId = nil;
        self.isLogin = NO;
    }
    return res;
}

- (void)requestLoginWentWrong:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    Log(@"res : %@",tResponseStr);
    NSError *error = [request error];
    Log(@"failed : %@",[error description]);
    self.isLogin = NO;
    self.sessionId = nil;
    self.userName = nil;
    self.userId = nil;
}

#pragma ---------注册方法----------
-(BOOL)registerWithEmail:(NSString *)pEmail password:(NSString *)pPassWord username:(NSString *)pUserName
{
//    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:REGISTER_URL]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setAllowCompressedResponse:YES];
//    [request setPostValue:pEmail forKey:@"email"];
//    [request setPostValue:pPassWord forKey:@"password"];
//    [request setPostValue:@"保密" forKey:@"sex"];
//    [request setPostValue:pUserName forKey:@"username"];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIFormDataRequest_POST(REGISTER_URL);
    [request setPostValue:pEmail forKey:@"email"];
    [request setPostValue:pPassWord forKey:@"password"];
    [request setPostValue:@"保密" forKey:@"sex"];
    [request setPostValue:pUserName forKey:@"username"];
    [request setDelegate:self];
    [request startSynchronous];
    NSError *error = [request error];
    BOOL succ = NO;
    if(!error){
        NSString *tResponseStr = [request responseString];
        SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
        id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
        [tJsonParser release], tJsonParser = nil;
        if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
            succ = [[(NSDictionary *)tJsonObjects objectForKey:@"success"] boolValue];
            if (succ) {
                self.registerErrInfo = @"注册成功";
                Log(@"success");
            } else {
                self.registerErrInfo = [NSString stringWithFormat:@"%@",[(NSDictionary *)tJsonObjects objectForKey:@"error_info"]];
                Log(@"failed : %@",self.registerErrInfo);
            }
        }else{
            self.registerErrInfo = @"服务器异常,请稍后再试";
            Log(@"failed : %@",self.registerErrInfo);
        }
    }else{
        self.registerErrInfo = @"网络异常,请稍后再试";
        Log(@"failed : %@",[error description]);
    }
    return succ;
}

-(void)logout{
//    [home.jokeActionBar setUserState:home.jokeActionBar.userStateLogout]; //改变状态机
    self.isLogin = NO;
    self.sessionId = nil;
    self.userName = nil;
    self.userId = nil;
    self.password = nil;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject:password forKey:@"password"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"logout" object:self];
}

-(void)loginWithOauth {
    
}

@end
